from datetime import datetime
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import IsAuthenticated, AllowAny
from rest_framework.views import APIView
from django.http import Http404
from ordering.models import Order
from ordering.serializers import OrderSerializer
from django.contrib.auth.models import User
from django.db import transaction
from catalogue.models import Foods
from rest_framework.authentication import TokenAuthentication

# 视图类


class OrderView(APIView):
    # 只有登录才可访问
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    # permission_classes = [AllowAny]

    def get(self, request):
        try:
            # 需要更改
            user = User.objects.get(pk=1)
            oid_list = user.orders.all().values_list("oid").distinct()
            data = {}
            for oid in oid_list:
                sums = 0
                order = Order.objects.filter(oid=oid[0])
                for o in order:
                    sums += o.foods.price * o.count
                serializer = OrderSerializer(order, many=True)
                data[oid[0]] = serializer.data
                data[oid[0] + "_sum"] = sums
            return Response(data)
        except user.DoesNotExist:
            return Response({"error": "类型查询失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def post(self, request):
        oid = datetime.now().strftime('%Y%m%d%H%M%S')
        params = request.data
        fids = params.get("fids", None)
        print("fids --> ", fids, type(fids))
        counts = params.get("counts", None)
        address = params.get("address", None)
        deliver = params.get("deliver", None)
        # todo: add mask
        user = request.user
        for fid, count in zip(fids, counts):
            foods = Foods.objects.get(id=fid)
            data = {
                "oid": oid,
                "count": count,
                "foods": foods,
                "address": address,
                "deliver": deliver,
                "user": user,
            }
            print("data --> ", data)
            order = Order.objects.create(**data)
            if order.created:
                order.save()
            else:
                return Response({"error": "创建订单失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

        return Response({"msg": True})


class DeleteView(APIView):
    # 只有登录才可访问
    authentication_classes = [TokenAuthentication]
    permission_classes = [IsAuthenticated]
    # permission_classes = [AllowAny]

    transaction.atomic
    def post(self, request):
        params = request.data
        oid = params.get("oid", None)
        try:
            order = Order.objects.filter(oid=oid, user=request.user).all()
            order.delete()
            return Response({"msg": True})
        except order.DoesNotExist:
            transaction.rollback()
            return Response({"error": "删除订单失败"}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
